﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ProgNetComponents.Data.SqlCe;
using ProgNetComponents.Classes;
using DevExpress.XtraEditors.Repository;

namespace BuildHelper.Work.Tools
{
    public partial class FormSqlFuncGen : Form
    {
        public FormSqlFuncGen()
        {
            InitializeComponent();
            this.gridControl1.DataSource = dt;
        }
        private DataTable dt = new DataTable();
        Setup.ProcedurySql.ProceduryDataSet ds = new Setup.ProcedurySql.ProceduryDataSet();
        List<RepositoryItemLookUpEdit> browser = new List<RepositoryItemLookUpEdit>();
        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            base.OnFormClosed(e);
            var br = browser.ToArray();
            foreach (var b in br)
                b.Dispose();
            browser.Clear();
        }
        private void lueProc_EditValueChanged(object sender, EventArgs e)
        {
            dt.Clear();
            dt.Columns.Clear();
            ds.Clear();
            gridView1.Columns.Clear();
            var br = browser.ToArray();
            foreach (var b in br)
                b.Dispose();
            browser.Clear();

            if (lueProc.EditValue.IsNotNull())
            {
                using (SqlCeDataManager m = new SqlCeDataManager())
                {
                    m.AddTableDef(ds.STP_SQL_FUNC, "SELECT * FROM STP_SQL_FUNC WHERE STP_SQLF_ID = @ID");
                    m.AddTableDef(ds.STP_SQL_FUNC_PARAMS, "SELECT * FROM STP_SQL_FUNC_PARAMS WHERE STP_SQLFP_FUNC = @ID");
                    m.FillDataSet(ds, new NamedObject("@ID", lueProc.EditValue));
                }
                foreach (DataRow r in ds.STP_SQL_FUNC_PARAMS.Select(null, "STP_SQLFP_POZYCJA"))
                {
                    var c = dt.Columns.Add(r["STP_SQLFP_KOD"].AsString());
                    c.DefaultValue = r["STP_SQLFP_DEFAULT"].AsString();
                    c.Caption = r["STP_SQLFP_NAZWA"].AsString();
                }
                gridView1.PopulateColumns();
                foreach (DataRow r in ds.STP_SQL_FUNC_PARAMS.Select("STP_SQLFP_BROWSER IS NOT NULL", "STP_SQLFP_POZYCJA"))
                {
                    RepositoryItemLookUpEdit rep = new RepositoryItemLookUpEdit();
                    this.browserProvider1.GetSettings(rep).BrowserId = r["STP_SQLFP_BROWSER"].AsString();
                    gridView1.Columns[r["STP_SQLFP_KOD"].AsString()].ColumnEdit = rep;
                    browser.Add(rep);
                }
            }
        }
    }
}
